/*
 * @Author: wjk
 * @Date: 2020-01-19 10:54:57
 * @LastEditors: wjk
 * @LastEditTime: 2020-02-27 14:11:34
 * @description: 智齿客服
 */
import { getOrderStateText, getUserLevelName } from '@/utils/common'
// import { mineApi } from '@/apis'
import { h5NavigateTo } from '@/utils/navigateTo'
import store from '../stores'

function filterObjectToUrlParams(obj) {
  const keys = Object.keys(obj)
  if (keys.length <= 0) { return }
  let str = ''
  for (let i = 0; i < keys.length; i++) {
    const key = keys[i]
    const value = obj[key]
    str += (key + '=' + encodeURIComponent(value) + '&')
  }
  str = str.substring(0, str.length - 1)
  return str
}

export const sobotService = async(item, type) => {
  const url = await sobotMicro(item, type)
  // console.log('url', url)
  h5NavigateTo(url)
  // console.log('h5NavigateTo', h5NavigateTo)
  return url
}

export const sobotMicro = async(item, type, target) => {
  const user = store.getters.user
  if (!user) return ''
  let sessionfrom = ''
  let params = {}
  let baseInfo = {
    partnerId: user.uid,
    uname: user.nickname,
    tel: user.mobile,
    face: user.head_img
  }
  // 如果附带商品信息
  if (item) {
    // 判断是否为取消（超时）订单,有order_no字段则为以上两种情况，需要发送订单信息; 其他情况则为在商品详情页打开，需要传递商品信息
    if (item.order_no) {
      // 自定义字段
      params = {
        // 订单号
        '订单号': item.order_no,
        // 问题描述
        '问题': '',
        // 订单状态
        '订单状态': getOrderStateText(item.status),
        // 下单时间
        '下单时间': new Date(item.order_time * 1000).toString(),
        // 用户等级
        '用户等级': getUserLevelName(user.current_member_card_type)
      }
    } else {
      // params = {
      //   // 用户id
      //   card_title: item.title,
      //   card_url: item.shareUrl || '',
      //   card_desc: item.subtitle,
      //   card_note: '¥ ' + item.vip_price || item.price,
      //   card_picture: item.pic
      // }
      let note = ''
      if (item.type === 4) {
        note = '¥ ' + item.ComboPriceMin + '-' + item.ComboPriceMax
      } else {
        note = '¥ ' + item.vip_price || item.price
      }
      const baseParams = {
        // 用户id
        card_title: item.title,
        card_url: item.shareUrl || '',
        card_desc: item.subtitle,
        card_note: note,
        card_picture: item.pic || item.image
      }
      baseInfo = Object.assign(baseInfo, baseParams)
    }
  }
  const param = JSON.stringify(params)
  baseInfo = filterObjectToUrlParams(baseInfo)
  // 生产环境
  if (type === 'navigate') {
    // if (getConfig()) {
    //   await updateAppConfig()
    // }
    const url = 'https://chat.sobot.com/chat/h5/v2/index.html?sysnum=1c46f6c48d5a4598897804c222ae4192&' + baseInfo + '&customer_fields=' + param
    // 智齿客服提供测试账号
    // let url = 'https://chat.sobot.com/chat/h5/v2/index.html?sysnum=ff7fe2f40f1944f8bc9d50e1ac83835a&channelid=2&' + baseInfo + '&customer_fields=' + param
    // let url = 'https://www.sobot.com/chat/h5/index.html?sysNum=31df00a96d5644e6a0547fad72e37242&back=1&' + baseInfo + '&customerFields=' + param
    const result = getServiceJudge(item, url, target)
    // #ifdef H5
    location.href = result
    // #endif
    return result
  }
  sessionfrom = `sobot|${user.nickname}|${user.head_img}|${getServiceJudge(item, param, target)}`
  return sessionfrom
}

export const getServiceJudge = (item, url, target) => {
  const storage = uni.getStorageSync('__app_config_info__')
  if (storage) {
    let serverInfo = JSON.parse(storage)// 如果有配置中心数据
    if (serverInfo && serverInfo.common) {
      serverInfo = JSON.parse(serverInfo.common).server_skill
      if (item) {
        if (Number(item.from_type) === 22) {
          // 38礼包专属客服
          let id = serverInfo['22']
          if (!id) {
            id = serverInfo['default']
          }
          url += url + '&groupid=' + id
        } else {
          url += url + '&groupid=' + serverInfo['default']
        }
      } else if (target) {
        if (Number(target) === 22) {
          let id = serverInfo['22']
          if (!id) {
            id = serverInfo['default']
          }
          url += url + '&groupid=' + id
        }
      } else {
        url += url + '&groupid=' + serverInfo['default']
      }
    }
  }
  return url
}

// export const getConfig = () => {
//   // 配置中心数据缓存
//   const config_serVision = uni.getStorageSync('__app_config_vision__')
//   let getConfig = false
//   // 如果有版本信息
//   if (config_serVision) {
//     let configCenter = uni.getStorageSync('__app_config_info__')
//     // 如果info已有数据
//     if (configCenter) {
//       configCenter = JSON.parse(configCenter)
//       // 监测data是否为空,为空则为第一次取数据
//       if (!configCenter.data) {
//         getConfig = true
//       } else {
//         const config_localVision = configCenter.vision
//         if (config_serVision !== config_localVision) {
//           // 如果版本有变，则并重新请求接口获取最新配置信息
//           configCenter.vision = config_serVision
//           getConfig = true
//         }
//       }
//     } else {
//       getConfig = true
//     }
//   } else {
//     getConfig = true
//   }
//   return getConfig
// }

// export const updateAppConfig = async() => {
//   const config_serVision = uni.getStorageSync('__app_config_vision__')
//   const res = await mineApi.getConfigCenter({ acmVersion: config_serVision })
//   if (res.data) {
//     const configCenter = JSON.parse(uni.getStorageSync('__app_config_info__'))
//     configCenter.data = JSON.parse(res.data)
//     uni.setStorage({
//       key: '__app_config_info__',
//       data: JSON.stringify(configCenter)
//     })
//   }
//   return res
// }
